﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
//
using DHNetSDK;
using DHPlaySDK;
using Microsoft.Win32;
using DLLTest.OpertionClass;
using DLLTest.OpretionClass;
using System.Diagnostics;
using System.Security.AccessControl;

namespace DLLTest
{
    public partial class frm_Main : Form
    {
        #region Const Fields

        public const int PANEL_COUNT = 4; // 默认连续取 4 个视频窗口

        #endregion

        public static Panel MaxPanel { get; private set; }
        public static Panel BasePanel { get; private set; }

        /// <summary>
        /// 设备信息
        /// </summary>
        private NET_DEVICEINFO deviceInfo;

        /// <summary>
        /// 定义的登录次数
        /// </summary>
        private const Int32 tLongin = 300;

        //通道信息
        public string Panchannel = "";//panel所选通道
        public string Panlogin = "";//panel所对应的LoginID
        public string Panreadplay = "";//panel所选的实时播放句柄

        /// <summary>
        /// 设备用户登录ＩＤ
        /// </summary>
        public int pLoginID;

        #region 设备登陆所需信息
        /// <summary>
        /// 设备登陆所需信息
        /// </summary>
        public string ID = "";//TreeView选择号
        public string PARENTID = "";//TreeView所选父ID
        public string DVRIP = "";//设备登陆IP地址
        public string DVRUSERNAME = "";//设备登陆用户名
        public string DVRPWD = "";//设备登陆密码
        public string DVRPROT = "";//设备登陆端口
        public int TREE_INDEX = -1; // 所选树结点的序号
        public string CHANNELNO = "-1";//记录通道号
        public string PlayMode = "0";//记录通道状态
        #endregion

        /// <summary>
        /// 读取ini文件
        /// </summary>
        iniOperate inioperate = new iniOperate();
        private string strDPath = null;
        private string srcpath = null;

        /// <summary>
        /// 数据操作类
        /// </summary>
        DataOperate dataoperate = new DataOperate();

        /// <summary>
        /// 使用TreeView操作
        /// </summary>
        TreeViewOpertion treeopertion = new TreeViewOpertion();

        /// <summary>
        /// 使用分屏类
        /// </summary>
        PanelOpertion panelopertion = new PanelOpertion();

        /// <summary>
        /// 加密解密
        /// </summary>
        EncDecryOpertion dncdec = new EncDecryOpertion();

        /// <summary>
        /// 大华PTZ控制
        /// </summary>
        PtzOpertion dhptz = new PtzOpertion();

        /// <summary>
        /// 程序消息提示Title
        /// </summary>
        private const string pMsgTitle = "创智科技股份有限公司";

        /// <summary>
        /// 最后操作信息显示格式
        /// </summary>
        private const string pErrInfoFormatStyle = "代码:errcode;\n描述:errmSG.";

        //2013年11月11日添加
        /// <summary>
        /// 当前回放的文件信息
        /// </summary>
        NET_RECORDFILE_INFO fileInfo;

        /// <summary>
        /// 播放方式
        /// </summary>
        private int playBy = 0;

        /// <summary>
        /// 实时播放句柄保存
        /// </summary>
        //private int[] pRealPlayHandle;
        private int pRealPlayHandle = 0;

        /// <summary>
        /// 回放句柄保存
        /// </summary>
        //private int[] pPlayBackHandle;
        private int pPlayBackHandle;

        /// <summary>
        /// 回放通道号
        /// </summary>
        private int pPlayBackChannelID;

        /// <summary>
        /// 上次点击的PictureBox控件
        /// 2013年11月11日改为panel控件
        /// </summary>
        //private PictureBox oldPicRealPlay;
        private Panel oldpicPlayMain;
        /// <summary>
        /// 当前点击的PictureBox控件
        /// 2013年11月11日改为panel控件
        /// </summary>
        //private PictureBox picRealPlay;
        private Panel picPlayMain;

        //2013年11月11日添加
        /// <summary>
        /// 实时监视句柄
        /// </summary>
        public int uRealHandle;

        /// <summary>
        /// 实时监视数据回调
        /// </summary>
        private fRealDataCallBack cbRealData;

        /// <summary>
        /// 断开连接回调
        /// </summary>
        private fDisConnect disConnect;

        /// <summary>
        /// 是否己设置实时数据回调
        /// </summary>
        private bool blnSetRealDataCallBack = false;

        /// <summary>
        /// 构造函数
        /// </summary>
        public frm_Main()
        {
            InitializeComponent();

            MaxPanel = maxPanel;
            BasePanel = picPlayMain0;


            // 获得屏幕数
            getScreenNums();
        }

        #region Screen

        /// <summary>
        /// 获得屏幕数量
        /// </summary>
        private void getScreenNums()
        {
            for (int i = 0; i < Screen.AllScreens.Length; i++)
            {
                TSMenuWallDisplay.DropDownItems.Add("显示通道:" + i, null, TSMenuWallDisplayItem_Click);
            }
        }

        private void TSMenuWallDisplayItem_Click(object sender, EventArgs e)
        {
            try
            {
                string screenChannel = (sender as ToolStripDropDownItem).Text;
                string portNum = screenChannel.Substring(screenChannel.IndexOf(':') + 1);

                frm_Wall wndWall = new frm_Wall()
                {
                    StartPosition = FormStartPosition.Manual,
                    Location = new Point(Screen.AllScreens[int.Parse(portNum)].Bounds.Left,
                        Screen.AllScreens[int.Parse(portNum)].Bounds.Top),
                };

                wndWall.Show(); // 显示窗口
                if (PanelOpertion.SelectedPanel.Tag != null &&
                    PanelOpertion.SelectedPanel.Tag.ToString().Split(',').Length == 7)
                {
                    // a. 先停止小窗口中的视频
                    string[] leafTag = PanelOpertion.SelectedPanel.Tag.ToString().Split(',');
                    DHClient.DHStopRealPlay(Convert.ToInt32(leafTag[6])); // 停止实时监控，需要传递实时监控句柄
                    PanelOpertion.SelectedPanel.Refresh();

                    // b. 再播放上墙窗口中的视频
                    wndWall.Tag = PanelOpertion.SelectedPanel.Tag.ToString().Substring(0,
                        PanelOpertion.SelectedPanel.Tag.ToString().LastIndexOf(',')); // 去 realPlayHandle

                    string[] wallPanelTag = wndWall.Tag.ToString().Split(',');
                    int pRealPlayHandle = DHClient.DHRealPlay(int.Parse(wallPanelTag[4]),
                        Convert.ToInt32(wallPanelTag[5]), wndWall.Handle); //只取数据不播放

                    wndWall.Tag = string.Format("{0},{1}", wndWall.Tag, pRealPlayHandle); // 得到最新的 wndWall.Tag: ip,port,user,pwd,loginID,channel,realPlayHandle
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }

        #endregion

        /// <summary>
        /// 实时监视数据回调数据处理
        /// </summary>
        /// <param name="lRealHandle"></param>
        /// <param name="dwDataType"></param>
        /// <param name="pBuffer"></param>
        /// <param name="dwBufSize"></param>
        /// <param name="dwUser"></param>
        private void cbRealDataFun(int lRealHandle, UInt32 dwDataType, IntPtr pBuffer, UInt32 dwBufSize, IntPtr dwUser)
        {
            DHPlay.DHPlayControl(PLAY_COMMAND.InputData, 0, pBuffer, dwBufSize);//此处第二个参数nPort参数要与网络实时监控数据的取得的RealHandle对应
        }

        private void frm_Main_Load(object sender, EventArgs e)
        {
            disConnect = new fDisConnect(DisConnectEvent);//设备断开处理            
            bool blnInit = DHClient.DHInit(disConnect, IntPtr.Zero);//初始化状态
            DHClient.DHSetEncoding(LANGUAGE_ENCODING.gb2312);//字符编码格式设置，默认为gb2312字符编码，如果为其他字符编码请设置
            pRealPlayHandle = 0;//实时句柄保存           
            //首先把注册表信息写好，并且给后期提取注册表信息做第一步工作           
            RegistryOperate reg = new RegistryOperate();
            reg.isRegedit();
            //读取注册表键值,并解密
            RegistryOperate regedit = new RegistryOperate();
            string retkey = regedit.isOpenReg();
            Int32 tLong; //使用次数写入注册表
            if (retkey == "0")//如果子项里无注册号
            {
                this.Text = "创智视频监控系统(未注册)";
                FileAcc();//更改文件权限
                btnRegProc.Enabled = true;
                MessageBox.Show("您现在使用的是试用版，该软件可以免费试用"+tLongin+"次！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                try
                {
                    //获取注册表值
                    tLong = (Int32)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\angel", "UseTimes", 0);
                    MessageBox.Show("感谢您已使用了" + tLong + "次", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch
                {
                    //写入注册表信息
                    Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\angel", "UseTimes", 0, RegistryValueKind.DWord);
                    MessageBox.Show("欢迎新用户使用本软件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                tLong = (Int32)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\angel", "UseTimes", 0);
                if (tLong < tLongin)
                {
                    int Times = tLong + 1;
                    //将软件使用次数写入注册表  
                    Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\angel", "UseTimes", Times);
                }
                else
                {
                    MessageBox.Show("试用次数已到", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
                    Application.Exit();
                }
            }
            else//有wxk.INI子键，有注册号码,
            {
                //ini读取配置，本次采用读取INI文件信息进行比对，速度快
                strDPath = Application.StartupPath;
                srcpath = strDPath.Substring(0, strDPath.LastIndexOf("\\")).Substring(0, strDPath.Substring(0, strDPath.LastIndexOf("\\")).LastIndexOf("\\")) + "\\DataBase\\db_DLL.ini";
                inioperate.IniFile();
                //提取ini文件为做修改的内容后加密
                string getcode = inioperate.IniReadValue("软件注册", "注册码");
                retkey = dncdec.Decrypt(retkey);
                if (retkey == getcode)//如果已经有了注册号码
                {
                    this.Text = "创智视频监控系统(已注册)";
                    btnRegProc.Enabled = false;
                }
                else
                {
                    //MessageBox.Show("注册码不一样");
                    this.Text = "创智视频监控系统(未注册)";
                    btnRegProc.Enabled = true;
                    MessageBox.Show("您现在使用的是试用版，该软件可以免费试用"+tLongin+"次！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //使用次数写入注册表
                    try
                    {
                        //获取注册表值
                        tLong = (Int32)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\angel", "UseTimes", 0);
                        MessageBox.Show("感谢您已使用了" + tLong + "次", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch
                    {
                        //写入注册表信息
                        Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\angel", "UseTimes", 0, RegistryValueKind.DWord);
                        MessageBox.Show("欢迎新用户使用本软件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    tLong = (Int32)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\angel", "UseTimes", 0);
                    if (tLong < tLongin)
                    {
                        int Times = tLong + 1;
                        //将软件使用次数写入注册表  
                        Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\angel", "UseTimes", Times);
                    }
                    else
                    {
                        MessageBox.Show("试用次数已到", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        Application.Exit();
                    }
                }
            }    //读取注册表键值语句结束             
            UpTree();//更新设备树
            btnScreen4.PerformClick();
        }

        /// <summary>
        /// 更新树列表
        /// </summary>
        public void UpTree()
        {
            //
            //在TreeView中显示数据
            //清空TreeView的内容
            treeView1.Nodes.Clear();
            //递归函数，0为根节点的父节点ParentID的值
            treeopertion.treeView3 = treeView1;
            treeopertion.AddTreeView(0, (TreeNode)null);//获取树节点
        }

        /// <summary>
        /// 设备断开连接处理
        /// </summary>
        /// <param name="lLoginID"></param>
        /// <param name="pchDVRIP"></param>
        /// <param name="nDVRPort"></param>
        /// <param name="dwUser"></param>
        private void DisConnectEvent(int lLoginID, StringBuilder pchDVRIP, int nDVRPort, IntPtr dwUser)
        {
            MessageBox.Show("设备用户断开连接！", pMsgTitle);
        }

        /// <summary>
        /// 抓图处理代码
        /// </summary>
        /// <param name="hPlayHandle">播放句柄</param>
        /// <param name="bmpPath">图像促存路径</param>
        private void CapturePicture(int hPlayHandle, string bmpPath)
        {
            if (DHClient.DHCapturePicture(hPlayHandle, bmpPath))
            {
                //抓图成功处理
                MessageBox.Show("抓图成功!", pMsgTitle);
            }
            else
            {
                //抓图失败处理
                MessageBox.Show("抓图失败!", pMsgTitle);
            }
        }

        /// <summary>
        /// 抓图按钮按下
        /// </summary>
        /// <param name="hPlayHandle"></param>
        private void CapturePicture(int hPlayHandle)
        {
            //默认保存路径为执行文件exe的目录下
            //string bmpPath = Application.StartupPath + @"\DH_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".bmp";
            //,2013-11-13修改为相对路径
            string bmpPath = Application.StartupPath + @".\dhPic\DH_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".bmp";
            //抓图处理
            CapturePicture(hPlayHandle, bmpPath);
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        /// <summary>
        /// 窗口关闭处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frm_Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            //string[] panUD = PanelOpertion.SelectedPanel.Tag.ToString().Split(',');
            //string Panlogin = panUD[4].ToString();
            ////string pLoginID = panUD[6].ToString();
            //bool result = DHClient.DHLogout(Convert.ToInt32(Panlogin));
            //        if (result == true)
            //        {                       
            //            MessageBox.Show("注销成功");
            //        }
            //        else
            //        {
            //            //报最后一次操作的错误信息
            //            MessageBox.Show(DHClient.LastOperationInfo.ToString(pErrInfoFormatStyle), pMsgTitle);
            //        }               
            //释放SDK资源
            DHClient.DHCleanup();
        }
        /// <summary>
        /// 停止按钮按下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStopRealPlay2_Click(object sender, EventArgs e)
        {
            switch (picPlayMain.Name)
            {
                case "picPlayMain0":
                    MessageBox.Show("picPlayMain0");
                    break;
            }
        }

        /// <summary>
        /// 云台扩展控制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPTZControl_Click1(object sender, EventArgs e)
        {
            frm_PTZControl fPTZ = new frm_PTZControl();
            fPTZ.LoginID = pLoginID;
            fPTZ.ShowDialog();
        }
        /// <summary>
        /// 云台控制按钮按下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPTZControl_Click(object sender, EventArgs e)
        {
            if (PanelOpertion.SelectedPanel == null)
                return;

            ushort stepValue = 1;
            if (txtStep.Text.Length > 0)
            {
                stepValue = ushort.Parse(txtStep.Text.ToString());
            }
            else
            {
                MessageBox.Show("请输入步进(速度)值！", pMsgTitle);
                return;
            }
            string[] panUD = PanelOpertion.SelectedPanel.Tag.ToString().Split(',');
            string Panlogin = panUD[4].ToString();
            string Panchannel = panUD[5].ToString();
            //MessageBox.Show("0=" + Panlogin +","+ "1=" + Panlogin1 +","+ "2=" + Panlogin2+"," + "3=" + Panlogin3+"," + "4=" + Panlogin4+"," + "5=" + Panlogin5+"," + "6=" + Panlogin6);
            //获取Button的Name
            string btnname = ((Button)sender).Name;
            # region <<**********云台控制代码**********>>
            dhptz.DHPTZContrer(btnname, Convert.ToInt32(Panlogin), Convert.ToInt32(Panchannel), stepValue, 1);
            #endregion
        }
        /// <summary>
        /// 云台控制[按钮鼠标抬起]处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPTZControl_MouseUp(object sender, MouseEventArgs e)
        {
            if (PanelOpertion.SelectedPanel == null)
                return;

            ushort stepValue = 1;
            if (txtStep.Text.Length > 0)
            {
                stepValue = ushort.Parse(txtStep.Text.ToString());
            }
            else
            {
                MessageBox.Show("请输入步进(速度)值！", pMsgTitle);
                return;
            }
            string[] panUD = PanelOpertion.SelectedPanel.Tag.ToString().Split(',');
            string Panlogin = panUD[4].ToString();
            string Panchannel = panUD[5].ToString();
            //MessageBox.Show("0=" + Panlogin +","+ "1=" + Panlogin1 +","+ "2=" + Panlogin2+"," + "3=" + Panlogin3+"," + "4=" + Panlogin4+"," + "5=" + Panlogin5+"," + "6=" + Panlogin6);
            //获取Button的Name
            string btnname = ((Button)sender).Name;
            # region <<**********云台控制代码**********>>
            dhptz.DHPTZContrer(btnname, Convert.ToInt32(Panlogin), Convert.ToInt32(Panchannel), stepValue, 3);
            #endregion
        }
        /// <summary>
        /// 云台控制[按钮鼠标按下]处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPTZControl_MouseDown(object sender, MouseEventArgs e)
        {
            if (PanelOpertion.SelectedPanel == null)
                return;

            ushort stepValue = 1;
            if (txtStep.Text.Length > 0)
            {
                stepValue = ushort.Parse(txtStep.Text.ToString());
            }
            else
            {
                MessageBox.Show("请输入步进(速度)值！", pMsgTitle);
                return;
            }
            string[] panUD = PanelOpertion.SelectedPanel.Tag.ToString().Split(',');
            string Panlogin = panUD[4].ToString();
            string Panchannel = panUD[5].ToString();
            //MessageBox.Show("0=" + Panlogin +","+ "1=" + Panlogin1 +","+ "2=" + Panlogin2+"," + "3=" + Panlogin3+"," + "4=" + Panlogin4+"," + "5=" + Panlogin5+"," + "6=" + Panlogin6);
            //获取Button的Name
            string btnname = ((Button)sender).Name;
            # region <<**********云台控制代码**********>>
            dhptz.DHPTZContrer(btnname, Convert.ToInt32(Panlogin), Convert.ToInt32(Panchannel), stepValue, 2);
            #endregion
        }

        /// <summary>
        /// 抓图按钮按下处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCapturePicture_Click(object sender, EventArgs e)
        {
            //CapturePicture(pRealPlayHandle);
            if (PanelOpertion.SelectedPanel == null)
                return;
            string[] panUD = PanelOpertion.SelectedPanel.Tag.ToString().Split(',');
            string Panreadplay = panUD[6].ToString();
            CapturePicture(Convert.ToInt32(Panreadplay));
        }

        /// <summary>
        /// 视频流录像转换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDataRecord_Click(object sender, EventArgs e)
        {
            frm_DataRecord fdr = new frm_DataRecord();    //数据流录像演示窗口            
            fdr.ShowDialog();
        }

        /// <summary>
        /// 网络视频文件下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRecordDownload_Click(object sender, EventArgs e)
        {
            frm_RecordDownload frmrecorddownload = new frm_RecordDownload();
            frmrecorddownload.ShowDialog();
        }

        private void btnRegProc_Click(object sender, EventArgs e)
        {
            //产品注册
            frm_Register frmregsiter = new frm_Register();
            frmregsiter.Show();
        }

        #region Tree

        /// <summary>
        /// 双击叶子结点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (treeView1.SelectedNode.Level != 2) // 只有叶子结点有效
                return;

            if (PanelOpertion.SelectedPanel != null && treeView1.SelectedNode.Tag != null)
            {
                if (PanelOpertion.SelectedPanel.Tag != null &&
                    PanelOpertion.SelectedPanel.Tag.ToString().Split(',').Length == 7)
                {
                    string[] leafTag = PanelOpertion.SelectedPanel.Tag.ToString().Split(',');
                    DHClient.DHStopRealPlay(Convert.ToInt32(leafTag[6])); // 停止实时监控，需要传递实时监控句柄
                }

                string[] nodeTag = treeView1.SelectedNode.Tag.ToString().Split(',');

                pRealPlayHandle = DHClient.DHRealPlay(int.Parse(nodeTag[4]),
                    Convert.ToInt32(e.Node.Name), PanelOpertion.SelectedPanel.Handle); // 只取数据不播放

                PanelOpertion.SelectedPanel.Tag = string.Format("{0},{1},{2}",
                    treeView1.SelectedNode.Tag, e.Node.Name, pRealPlayHandle); // PanelTag: ip,port,user,pwd,loginID,channel,realPlayHandle
            }
            else
                MessageBox.Show("没有选择窗口!");
        }

        /// <summary>
        /// 设备登陆【右键菜单】
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tSMItem1_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode.Tag != null)
            {
                string[] nodeTag = treeView1.SelectedNode.Tag.ToString().Split(',');
                deviceInfo = new NET_DEVICEINFO(); //设备用户信息获得
                int error = 0;

                pLoginID = DHClient.DHLogin(nodeTag[0], ushort.Parse(nodeTag[1]), nodeTag[2], nodeTag[3],
                    out deviceInfo, out error); //设备用户登录
                if (pLoginID != 0 && deviceInfo.byChanNum > 0)
                {
                    treeView1.SelectedNode.Tag = string.Format("{0},{1}",
                    treeView1.SelectedNode.Tag.ToString(), pLoginID); // NodeTag: ip,port,user,pwd,loginID

                    string[] exceptChannels = null;
                    bool isExcept = false; // 表示是否为排除的通道号

                    if (!string.IsNullOrEmpty(treeView1.SelectedNode.ToolTipText))
                    {
                        exceptChannels = treeView1.SelectedNode.ToolTipText.Split(','); // 得到所有排除的通道序列
                    }
                    for (int i = 0; i < deviceInfo.byChanNum; i++)
                    {
                        // Modify by: Fan 2014-02-27
                        // Desc: 只要含该数字的所有通道都被排除了，如：1, 11, 111...
                        //if (!string.IsNullOrEmpty(treeView1.SelectedNode.ToolTipText) &&
                        //    treeView1.SelectedNode.ToolTipText.Contains((i + 1).ToString())) // 排除通道号
                        //{
                        //    continue;
                        //}

                        isExcept = false; // 未排除
                        if (exceptChannels != null && exceptChannels.Length > 0)
                        {
                            foreach (string channel in exceptChannels) // 排除通道号
                            {
                                if (channel.Equals((i + 1).ToString()))
                                    isExcept = true;
                            }
                        }

                        if (isExcept)
                            continue;

                        TreeNode leafChannel = new TreeNode()
                        {
                            Name = i.ToString(),
                            Text = string.Format("通道{0}", i + 1),
                            Tag = treeView1.SelectedNode.Tag,
                        };

                        treeView1.SelectedNode.Nodes.Add(leafChannel);
                    }
                }
                else
                {
                    MessageBox.Show(DHClient.LastOperationInfo.ToString(pErrInfoFormatStyle),
                        pMsgTitle);
                }
            }
        }
        #endregion

        private void cMStrip_Opening(object sender, CancelEventArgs e)
        {
            if (treeView1.SelectedNode == null || treeView1.SelectedNode.Level == 2)
            {
                e.Cancel = true;
                return;
            }

            if (treeView1.SelectedNode.Level == 0) // 根
            {
                tSMItem1.Enabled = false;
                tSMItem2.Enabled = false;
                tSMItem3.Enabled = true;
            }
            else if (treeView1.SelectedNode.Level == 1) // 设备
            {
                tSMItem1.Enabled = false;
                tSMItem2.Enabled = true;
                tSMItem3.Enabled = false;
                if (treeView1.SelectedNode.Tag != null &&
                    treeView1.SelectedNode.Tag.ToString().Split(',').Length == 4) // 最初NodeTag：ip,port,user,pwd
                {
                    tSMItem1.Enabled = true;
                    tSMItem2.Enabled = false;
                    tSMItem3.Enabled = false;
                }
            }
        }

        /// <summary>
        /// 注销设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tSMItem2_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode.Tag != null)
            {
                string[] nodeTag = treeView1.SelectedNode.Tag.ToString().Split(',');
                if (nodeTag.Length >= 5 &&
                    DHClient.DHLogout(Convert.ToInt32(nodeTag[4])))
                {
                    // 1. 去 Tag 中的 loginID
                    treeView1.SelectedNode.Tag = treeView1.SelectedNode.Tag.ToString().Substring(0,
                        treeView1.SelectedNode.Tag.ToString().LastIndexOf(','));

                    // 2. 清空所有通道
                    treeView1.SelectedNode.Nodes.Clear();

                    // 3. 提示成功
                    MessageBox.Show("注销成功");
                }
                else
                    MessageBox.Show(DHClient.LastOperationInfo.ToString(pErrInfoFormatStyle), pMsgTitle); //报最后一次操作的错误信息
            }
        }

        /// <summary>
        /// 关闭视频
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TSMenuPanelClose_Click(object sender, EventArgs e)
        {
            if (PanelOpertion.SelectedPanel != null && 
                PanelOpertion.SelectedPanel.Tag != null)
            {
                string[] panelTag = PanelOpertion.SelectedPanel.Tag.ToString().Split(',');
                if (panelTag.Length >= 7 &&
                    DHClient.DHStopRealPlay(Convert.ToInt32(panelTag[6])))
                {
                    // 1. 去 Tag 中的 realPlayHandle与通道号
                    PanelOpertion.SelectedPanel.Tag = string.Join(",",
                        panelTag.Take(5).ToArray());

                    // 2. 刷新
                    PanelOpertion.SelectedPanel.Refresh();

                    // 3. 提示成功
                    //MessageBox.Show("停止实时视频成功");
                }
                else
                    MessageBox.Show(DHClient.LastOperationInfo.ToString(pErrInfoFormatStyle), pMsgTitle); //报最后一次操作的错误信息
            }
        }

        /// <summary>
        /// 关闭所有视频
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TSMenuPanelCloseAll_Click(object sender, EventArgs e)
        {
            if(PanelOpertion.PanelCurrentList != null &&
                PanelOpertion.PanelCurrentList.Count > 0)
            {
                foreach (Panel singlePanel in PanelOpertion.PanelCurrentList)
                {
                    if (singlePanel != null && singlePanel.Tag != null)
                    {
                        string[] panelTag = singlePanel.Tag.ToString().Split(',');
                        if (panelTag.Length >= 7 &&
                            DHClient.DHStopRealPlay(Convert.ToInt32(panelTag[6])))
                        {
                            // 1. 去 Tag 中的 realPlayHandle与通道号
                            singlePanel.Tag = string.Join(",", panelTag.Take(5).ToArray());

                            // 2. 刷新
                            singlePanel.Refresh();

                            // 3. 提示成功
                            //MessageBox.Show("停止实时视频成功");
                        }
                        //else
                            //MessageBox.Show(DHClient.LastOperationInfo.ToString(pErrInfoFormatStyle), pMsgTitle); //报最后一次操作的错误信息
                    }
                }
            }
        }

        private void btnTechnical_Click(object sender, EventArgs e)
        {
            frm_About frmabout = new frm_About();
            frmabout.Show();
        }

        private void btnScreen25_Click(object sender, EventArgs e)
        {
            panelopertion.SplitScreen(25, picPlayMain0);
        }

        private void btnScreen9_Click(object sender, EventArgs e)
        {
            panelopertion.SplitScreen(9, picPlayMain0);
        }

        private void btnScreen1_Click(object sender, EventArgs e)
        {
            panelopertion.SplitScreen(1, picPlayMain0);
        }

        private void btnScreen4_Click(object sender, EventArgs e)
        {
            panelopertion.SplitScreen(4, picPlayMain0);
        }

        private void btnScreen16_Click(object sender, EventArgs e)
        {
            panelopertion.SplitScreen(16, picPlayMain0);
        }

        private void btnScreen36_Click(object sender, EventArgs e)
        {
            panelopertion.SplitScreen(36, picPlayMain0);
        }

        private void maxPanel_DoubleClick(object sender, EventArgs e)
        {
            maxPanel.Visible = false;
            picPlayMain0.Visible = true;

            if (maxPanel.Tag != null &&
                maxPanel.Tag.ToString().Split(',').Length == 7)
            {
                // a. 先停止大窗口中的视频
                string[] leafTag = maxPanel.Tag.ToString().Split(',');
                DHClient.DHStopRealPlay(Convert.ToInt32(leafTag[6])); // 停止实时监控，需要传递实时监控句柄

                // b. 再播放小窗口中的视频
                PanelOpertion.SelectedPanel.Tag = maxPanel.Tag.ToString().Substring(0,
                    maxPanel.Tag.ToString().LastIndexOf(',')); // 去 realPlayHandle

                string[] panelTag = PanelOpertion.SelectedPanel.Tag.ToString().Split(',');
                int pRealPlayHandle = DHClient.DHRealPlay(int.Parse(panelTag[4]),
                    Convert.ToInt32(panelTag[5]), PanelOpertion.SelectedPanel.Handle); //只取数据不播放

                PanelOpertion.SelectedPanel.Tag = string.Format("{0},{1}", PanelOpertion.SelectedPanel.Tag, pRealPlayHandle); // 得到最新的 PanelTag: ip,port,user,pwd,loginID,channel,realPlayHandle
            }
        }

        /// <summary>
        /// 添加设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tSMItem3_Click(object sender, EventArgs e)
        {
            try
            {
                frm_DataBase frmdatabase = new frm_DataBase(UpTree);
                frmdatabase.ShowDialog();
            }
            catch (System.Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// 视频流实时录像
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TSMenuPanelRecorde_Click(object sender, EventArgs e)
        {
            frm_DataRecord fdr = new frm_DataRecord();    //数据流录像演示窗口            
            fdr.ShowDialog();
        }

        /// <summary>
        /// 网络视频文件下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TSMenuRecordeDowload_Click(object sender, EventArgs e)
        {
            //frm_RecordDownload frmrecorddownload = new frm_RecordDownload();
            //frmrecorddownload.ShowDialog();
            frm_PlayBackByFileSet frmplaybackfiles = new frm_PlayBackByFileSet();
            frmplaybackfiles.ShowDialog();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            showOnMonitor(1);//index=1
        }
        private void showOnMonitor(int showOnMonitor)
        {
            Screen[] sc;
            sc = Screen.AllScreens;
            if (showOnMonitor >= sc.Length)
            {
                showOnMonitor = 0;
            }
            this.StartPosition = FormStartPosition.Manual;
            this.Location = new Point(sc[showOnMonitor].Bounds.Left, sc[showOnMonitor].Bounds.Top);
            // If you intend the form to be maximized, change it to normal then maximized.
            this.WindowState = FormWindowState.Normal;
            this.WindowState = FormWindowState.Maximized;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            showOnMonitor(0);//index=0
        }

        #region 自动分屏上墙

        private frm_AutoSplitWall[] autoSplitWalls; // 记录大屏数，用于再次分屏时的销毁


        /// <summary>
        /// 销毁主界面中对应大屏
        /// </summary>
        /// <param name="indexWall">大屏位置序号</param>
        private void removeFromAutoSplitWalls(int indexWall)
        {
            autoSplitWalls[indexWall] = null;
        }

        /// <summary>
        /// 重置分屏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ResetSplitScreen_Click(object sender, EventArgs e)
        {
            try
            {
                // 1. 所有视频可用，背景黑色
                foreach (Panel singlePanel in PanelOpertion.PanelCurrentList)
                {
                    singlePanel.Enabled = true;
                    singlePanel.BackColor = Color.Black;
                }

                // 2. 停止大屏上的展示，还原主界面最初的展示
                foreach (frm_AutoSplitWall autoSplitWall in autoSplitWalls)
                {
                    if (autoSplitWall != null)
                    {
                        autoSplitWall.CloseForm();
                    }
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
            finally
            {
                btn_ResetSplitScreen.Enabled = false;
                ctMStrip1.Enabled = tabControl1.Enabled = groupBox3.Enabled = btn_AutoSplitScreen.Enabled = !btn_ResetSplitScreen.Enabled;
            }
        }

        /// <summary>
        /// 自动分屏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_AutoSplitScreen_Click(object sender, EventArgs e)
        {
            try
            {
                if (Screen.AllScreens.Length <= 1)
                {
                    MessageBox.Show("目前只有一个显示器，无法自动分屏上墙！");
                    return;

                }

                int index4Panel = 0; // 记录主窗口中的窗口序号，从 0 开始
                int count; // 记录循环次数，用于每个大屏中窗口的 Tag 赋值
                autoSplitWalls = new frm_AutoSplitWall[Screen.AllScreens.Length]; // 1. 确定大屏个数

                for (int i = 1; i < Screen.AllScreens.Length; i++)
                {
                    count = -1;
                    // 2. 初始化大屏
                    autoSplitWalls[i] = new frm_AutoSplitWall(removeFromAutoSplitWalls)
                    {
                        StartPosition = FormStartPosition.Manual,
                        Location = new Point(Screen.AllScreens[i].Bounds.Left,
                            Screen.AllScreens[i].Bounds.Top),
                        Tag = string.Format("{0},{1},{2}", index4Panel, PANEL_COUNT, i), // 主窗口中的开始窗口序号，截取个数【默认从第 j 个窗口起连续取 4 个窗口】，大屏序号
                    };

                    autoSplitWalls[i].Show(); // 3. 显示窗口
                    for (; index4Panel < PanelOpertion.PanelCurrentList.Count && ++count < PANEL_COUNT; index4Panel++)
                    {
                        PanelOpertion.PanelCurrentList[index4Panel].Enabled = false; // 视频不可用
                        PanelOpertion.PanelCurrentList[index4Panel].BackColor = Color.Gray; // 修改背景色

                        // 4. 对 Tag 进行赋值
                        if (PanelOpertion.PanelCurrentList[index4Panel].Tag != null &&
                            PanelOpertion.PanelCurrentList[index4Panel].Tag.ToString().Split(',').Length == 7)
                        {
                            // a. 先停止小窗口中的视频
                            string[] leafTag = PanelOpertion.PanelCurrentList[index4Panel].Tag.ToString().Split(',');
                            DHClient.DHStopRealPlay(Convert.ToInt32(leafTag[6])); // 停止实时监控，需要传递实时监控句柄
                            PanelOpertion.PanelCurrentList[index4Panel].Refresh();


                            // b. 再播放上墙窗口中的视频
                            autoSplitWalls[i].PanelList[count].Tag = PanelOpertion.PanelCurrentList[index4Panel].Tag.ToString().Substring(0,
                                PanelOpertion.PanelCurrentList[index4Panel].Tag.ToString().LastIndexOf(',')); // 去 realPlayHandle

                            string[] wallPanelTag = autoSplitWalls[i].PanelList[count].Tag.ToString().Split(',');
                            int pRealPlayHandle = DHClient.DHRealPlay(int.Parse(wallPanelTag[4]),
                                Convert.ToInt32(wallPanelTag[5]), autoSplitWalls[i].PanelList[count].Handle); //只取数据不播放

                            autoSplitWalls[i].PanelList[count].Tag = string.Format("{0},{1}", autoSplitWalls[i].PanelList[count].Tag, pRealPlayHandle); // 得到最新的 frm_AutoSplitWall.PanelTag: ip,port,user,pwd,loginID,channel,realPlayHandle
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
            finally
            {
                if (Screen.AllScreens.Length >= 2)
                {
                    btn_ResetSplitScreen.Enabled = true;
                    ctMStrip1.Enabled = tabControl1.Enabled = groupBox3.Enabled = btn_AutoSplitScreen.Enabled = !btn_ResetSplitScreen.Enabled;
                }
            }
        }

        #endregion

        /// <summary>
        /// 更改文件权限
        /// </summary>
         private void FileAcc()
        {
            FileSystemRights MyRight = 0;
            AccessControlType MyType = 0;
            //switch (this.comboBox1.Text)
            //{
            //    case "完全控制":
            //        MyRight = FileSystemRights.FullControl;
            //        break;
            //    case "修改":
            //        MyRight = FileSystemRights.Modify;
            //        break;
            //    case "读取和运行":
            //        MyRight = FileSystemRights.ReadAndExecute;
            //        break;
            //    case "读取":
            //        MyRight = FileSystemRights.Read;
            //        break;
            //    case "写入":
            //        MyRight = FileSystemRights.Write;
            //        break;
            //}
            //switch (this.comboBox2.Text)
            //{
            //    case "允许":
            //        MyType = AccessControlType.Allow;
            //        break;
            //    case "拒绝":
            //        MyType = AccessControlType.Deny;
            //        break;
            //}
            string strDPath = Application.StartupPath + "\\DataBase\\db_VWMS.mdb";
            MyRight = FileSystemRights.Modify;
            string b = @"Users";
            MyType = AccessControlType.Allow;
            try
            {
                FileAccessControl.AddFileSecurity(strDPath, b, MyRight, MyType);
                //MessageBox.Show("增加文件访问权限操作成功！", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception MyEx)
            {
                MessageBox.Show(MyEx.Message, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }
    }
}